package apobates.gui.formatter.service;

import apobates.gui.formatter.reader.JsonFileReader;
import apobates.gui.formatter.reader.RemoteForm;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import java.io.IOException;

/**
 * 异步获取JSON文件内容
 */
public class JsonFileService extends Service<String> {
    private RemoteForm remoteForm;

    public RemoteForm getRemoteForm() {
        return remoteForm;
    }

    public void setRemoteForm(RemoteForm remoteForm) {
        this.remoteForm = remoteForm;
    }

    @Override
    protected Task<String> createTask() {
        final String filePath = remoteForm.getFilePath();
        final String charsetName = (null != remoteForm.getFileEncoding() && !remoteForm.getFileEncoding().isEmpty()) ? remoteForm.getFileEncoding() : null;
        return new Task<String>() {
            @Override
            protected String call() throws IOException {
                return JsonFileReader.Builder.create(filePath).charset(charsetName).build().read();
            }
        };
    }
}
